package com.gjintel.test.holidays;

import com.ctc.wstx.util.DataUtil;
import com.gjintel.framework.holidayset.model.HolidaySet;
import com.gjintel.framework.holidayset.service.IHolidaySetService;
import com.gjintel.sdk.util.DateUtils;
import com.gjintel.test.holidays.model.HolidaysData;
import com.gjintel.test.holidays.model.HolidaysInfo;
import com.gjintel.test.holidays.model.HolidaysInfo1;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import okhttp3.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/12/21.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath*:applicationContext.xml")
public class PrintDate {
    //工作日
    public static final Integer WORKING_DAY = 0;

    //节假日
    public static final Integer HOLIDAY = 1;

    //加班
    public static final Integer OVERTIME_DAY = 2;

    //休息日
    public static final Integer OFF_DAY = 3;

    @Autowired
    private IHolidaySetService holidaySetService;

    @Test
    public void main() {
        int year = 2018;
        Map<String, HolidaysData> map = getWeekendsDay(year);//双休日
        map.putAll(getHolidays(year));//合并

        Date date = new Date();
        for (Map.Entry<String, HolidaysData> entry : map.entrySet()) {
            HolidaysData holidaysData = entry.getValue();
            HolidaySet holidaySet = new HolidaySet();

            holidaySet.setAt_year(String.valueOf(year));
            holidaySet.setAt_day(entry.getKey());
            holidaySet.setCreate_name("系统");
            holidaySet.setDelete_flag(0);
            String descript = holidaysData.getDescript();
            if (holidaysData.getType() == OVERTIME_DAY) {
                descript = "节假日补班";
            }
            holidaySet.setDescript(descript);
            holidaySet.setHoilday_type(holidaysData.getType());
            holidaySet.setUpdateTime(date);
            holidaySetService.saveOrUpdate(holidaySet);
        }

        int a = 0;
    }

    //获取指定年全年中的双休日
    public static Map<String, HolidaysData> getWeekendsDay(int year) {
        Map<String, HolidaysData> map = new TreeMap();
        Calendar calendar = new GregorianCalendar(year, 0, 1);
        int i = 1;
        while (calendar.get(Calendar.YEAR) < year + 1) {
            calendar.set(Calendar.WEEK_OF_YEAR, i++);//设置第几个星期 取值范围 1----52
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);//设置为星期日
            if (calendar.get(Calendar.YEAR) == year) {
                map.put(String.format("%tF", calendar), new HolidaysData(OFF_DAY, "周日"));
                //System.out.printf("星期天：%tF%n", calendar);
            }
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
            if (calendar.get(Calendar.YEAR) == year) {
                map.put(String.format("%tF", calendar), new HolidaysData(OFF_DAY, "周六"));
                //System.out.printf("星期六：%tF%n", calendar);
            }
        }
        return map;
    }

    /**
     * 发起get请求
     *
     * @param url
     * @param timeOut 秒 默认值10秒
     * @return
     */
    public static String httpGet(String url, Integer timeOut) {
        String result = null;
        if (timeOut <= 0) {
            timeOut = 10;
        }
        OkHttpClient client = new OkHttpClient.Builder().
                connectTimeout(timeOut, TimeUnit.SECONDS).
                readTimeout(timeOut, TimeUnit.SECONDS).
                build();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送httppost请求
     *
     * @param url
     * @param data 提交的参数为key=value&key1=value1的形式
     * @return
     */
    public static String httpPost(String url, String data) {
        String result = null;
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = httpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    //获取某年某月法定节假日
    public static Map<String, HolidaysData> getHolidays(int year, int month) {
        String res = httpGet("https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + year + "-" + month + "&resource_id=6018&t=" + System.currentTimeMillis(), 5);
        Map<String, HolidaysData> map = new TreeMap();
        try {
            HolidaysInfo holidaysInfo = new Gson().fromJson(res, HolidaysInfo.class);
            if (holidaysInfo != null) {
                for (HolidaysInfo.DataBean dataBean : holidaysInfo.getData()) {
                    for (HolidaysInfo.DataBean.HolidayBean holidayBean : dataBean.getHoliday()) {
                        for (HolidaysInfo.DataBean.HolidayBean.ListBean listBean : holidayBean.getList()) {
                            Date date = DateUtils.simpleDateFormat(listBean.getDate(), "yyyy-MM-dd");
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            if (calendar.get(Calendar.YEAR) == year) {
                                //排除其他年份的日期
                                String key = String.format("%tF", date);
                                Date festivalDate = DateUtils.simpleDateFormat(holidayBean.getFestival(), "yyyy-MM-dd");
                                String festival = String.format("%tF", festivalDate);
                                if (festival.equals("2017-10-04")) {
                                    int aaa = 0;
                                }
                                if (map.containsKey(key) == false || festival.equals(key)) {
                                    //有内容就不重复覆盖了
                                    map.put(key, new HolidaysData(Integer.parseInt(listBean.getStatus()), holidayBean.getName()));
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            try {
                HolidaysInfo1 holidaysInfo1 = new Gson().fromJson(res, HolidaysInfo1.class);
                if (holidaysInfo1 != null) {
                    for (HolidaysInfo1.DataBean dataBean : holidaysInfo1.getData()) {
                        for (HolidaysInfo1.DataBean.HolidayBean.ListBean listBean : dataBean.getHoliday().getList()) {
                            Date date = DateUtils.simpleDateFormat(listBean.getDate(), "yyyy-MM-dd");
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            if (calendar.get(Calendar.YEAR) == year) {
                                //排除其他年份的日期
                                String key = String.format("%tF", date);
                                Date festivalDate = DateUtils.simpleDateFormat(dataBean.getHoliday().getFestival(), "yyyy-MM-dd");
                                String festival = String.format("%tF", festivalDate);
                                if (festival.equals("2017-10-04")) {
                                    int aaa = 0;
                                }
                                if (map.containsKey(key) == false || festival.equals(key)) {
                                    //有内容就不重复覆盖了
                                    map.put(key, new HolidaysData(Integer.parseInt(listBean.getStatus()), dataBean.getHoliday().getName()));
                                }

                            }
                        }
                    }
                }
            } catch (Exception ex1) {
            }
        }
        return map;
    }

    //获取指定年全年中的法定节假日
    public static Map<String, HolidaysData> getHolidays(int year) {
        Map<String, HolidaysData> map = new TreeMap();
        for (int i = 0; i < 12; i++) {
            Map<String, HolidaysData> holidaysDataMap = getHolidays(year, i + 1);
            for (Map.Entry<String, HolidaysData> entry : holidaysDataMap.entrySet()) {
                if (map.containsKey(entry.getKey()) == false) {
                    map.put(entry.getKey(), entry.getValue());
                }
            }
        }
        return map;
    }
}